package com.example.books2.config;

import com.example.books2.entity.Book;
import com.example.books2.entity.User;
import jakarta.persistence.EntityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;

@Configuration
public class DataInitializer {

    @Autowired
    private EntityManager entityManager;
    
    @Autowired
    private PlatformTransactionManager transactionManager;

    @Bean
    public CommandLineRunner initData() {
        return args -> {
            TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
            transactionTemplate.execute(status -> {
                initializeData();
                System.out.println("测试数据初始化完成！");
                return null;
            });
        };
    }

    private void initializeData() {
        // 初始化图书
        Book[] books = {
            createBook("Java编程思想", "Bruce Eckel", "978-0131872486"),
            createBook("Spring实战", "Craig Walls", "978-1617294945"),
            createBook("算法导论", "Thomas H. Cormen", "978-0262033848"),
            createBook("设计模式", "Erich Gamma", "978-0201633610"),
            createBook("深入理解计算机系统", "Randal E. Bryant", "978-0131872487")
        };

        for (Book book : books) {
            entityManager.persist(book);
        }

        // 初始化用户
        User[] users = {
            createUser("张三", "zhangsan@example.com"),
            createUser("李四", "lisi@example.com"),
            createUser("王五", "wangwu@example.com"),
            createUser("赵六", "zhaoliu@example.com"),
            createUser("钱七", "qianqi@example.com")
        };

        for (User user : users) {
            entityManager.persist(user);
        }
    }

    private Book createBook(String title, String author, String isbn) {
        Book book = new Book();
        book.setTitle(title);
        book.setAuthor(author);
        book.setIsbn(isbn);
        book.setAvailable(true);
        return book;
    }

    private User createUser(String name, String email) {
        User user = new User();
        user.setName(name);
        user.setEmail(email);
        return user;
    }
} 